﻿using INTEX.DataBase;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Controls;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Windows;
using System.Windows.Data;
using WPFExcelReport.Helpers;
using System.Linq;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// </summary>
    public partial class FLTABMCO : DocumentBase
    {
        #region-------------Properties-----------------------
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        DataSet SResult;
        bool IsLoaded = false;
        DataRow rowevl = null;
        DataSet SetMap = null; 
        public DataSet dsResult;
        FLTABMCOData m_Data;  
        DataTable tbUser = null;
        DataRow dwData = null;
        ITXEXRPT ITXEXRPT = null;
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public SETINTEXDB SetProd
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetProd");
            }
        }

        BackgroundWorker bgWoker;
        CollectionViewSource vwEXSTOCK
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwEXSTOCK");
            }
        }
        DataRow dwEXSTOCK
        {
            get
            {
                if (vwEXSTOCK.View == null)
                    return null;
                if ((DataRowView)vwEXSTOCK.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwEXSTOCK.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwABCOST
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABCOST");
            }
        }
        DataRow dwABCOST
        {
            get
            {
                if (vwABCOST.View == null)
                    return null;
                if ((DataRowView)vwABCOST.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABCOST.View.CurrentItem).Row;
            }
        }

        CollectionViewSource vwEVLCOST
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwEVLCOST");
            }
        }
        DataRow dwEVLCOST
        {
            get
            {
                if (vwEVLCOST.View == null)
                    return null;
                if ((DataRowView)vwEVLCOST.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwEVLCOST.View.CurrentItem).Row;
            }
        }
      
        string MART
        {
            get
            {
                return m_Data.Left(txtMART.Text.ToString() + "                      ", 20);
            }
        }
        string FART
        {
            get
            {
                return m_Data.Left(txtFART.Text.ToString() + "                      ", 20);
            }
        } 
         
        BindingListCollectionView cvEVLCOST
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgEVLCOST.ItemsSource);
            }
        }
        BindingListCollectionView cvEVLCOSTM
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgEVLCOSTM.ItemsSource);
            }
        }
        string Year
        {
            get
            {
                if (txtYear.Text.Trim() == "")
                {
                    MessageBox.Show("请设定年限");
                }
                return Helpers.Helper.Left(txtYear.Text.ToString() + "    ", 5).Trim();
            }
            set
            {
                txtYear.Text = value;
            }
        }
        string Month
        {
            get
            {
                if (txtMonth.Text.Trim() == "")
                {
                    MessageBox.Show("请设定月份");
                }
                return Helpers.Helper.Left(txtMonth.Text.ToString() + "    ", 5).Trim();
            }
            set
            {
                txtMonth.Text = value;
            }
        }
        string user = "";
       
        #endregion
        public FLTABMCO()
        {
            InitializeComponent();
            this.Name = "原料成本分摊";
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            dicParamater["blBuildCellMastrix"] = false;
            base.SetUp(dicParamater);
            InitializeComponent(); 
            m_Data = new FLTABMCOData();
            ITXEXRPT = new ITXEXRPT();
            ITXEXRPT.Root = "C:\\IntexReport";
            ITXEXRPT.strCompany = app.company;
            ITXEXRPT.PrintType = "OpenExcel";
            user = (string)dicParamater["User"];
            Year = m_Data.year;
            if(m_Data.month=="01")
            {
                Year=(Convert.ToInt16( m_Data.year)-1).ToString();
                Month="12";
            }
            else
            {
                Year=m_Data.year;
                Month = Helpers.Helper.Right("00" + (Convert.ToInt16(m_Data.month) - 1).ToString(), 2);
            }            
            ReSetEnv();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (IsLoaded)
                    return;
                IsLoaded = true;
                vwEVLCOST.View.CurrentChanged += vwEVLCOST_CurrentChanged;
                bgWoker = new BackgroundWorker();
                bgWoker.DoWork += bgWoker_DoWork;
                bgWoker.RunWorkerCompleted += bgWoker_RunWorkerCompleted;                
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;
        }

        void bgWoker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            EventDispatcher.Instance.RaiseStatus("更新完成", StatusEventType.StopProgress);
        }

        void bgWoker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (dwData == null)
                return;
            EventDispatcher.Instance.RaiseStatus("开始更新", StatusEventType.StartProgress);
            m_Data.BuildData(dwData);
        }
        public void ReSetEnv()
        {

            DataSet setResult = new DataSet();
            try
            {
                setResult = m_Data.LoadEnv();

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void LoadData(DataRow dwInput)
        {
            try
            {
                DataSet SResult = new DataSet();
                //cvABPOS.CustomFilter = null;
                txtFART.Text = dwInput["FART"].ToString();
                txtMART.Text = dwInput["MART"].ToString();
                string filter = "MART='" + dwInput["MART"].ToString() + "' AND MVAR='" + dwInput["MVAR"].ToString() + "' AND LO='" + dwInput["LO"].ToString() + "'";
                cvEVLCOSTM.CustomFilter = filter;
                using (new LongOperation(this, "数据更新中"))
                {
                    SResult = m_Data.LoadDetail(dwInput);
                    SetProd.Clear();
                    SetProd.Merge(SResult);
                }
                if (vwABCOST.View != null)
                {
                    vwABCOST.View.MoveCurrentToFirst();
                }
                if (vwEXSTOCK.View != null)
                {
                    vwEXSTOCK.View.MoveCurrentToFirst();
                }     
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
               
            }
        }
        void vwEVLCOST_CurrentChanged(object sender, EventArgs e)
        {
            if (dwEVLCOST == null)
                return;
            if (rowevl == dwEVLCOST)
                return;
            rowevl = dwEVLCOST;          
            LoadData(dwEVLCOST);
           }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            ITXEXRPT.dsSource =SetData;
            ITXEXRPT.DocType = "FLTABMCO";
            ITXEXRPT.strExcelFile =  @"FLT\FLTABMCO.xls";
            string filename = ITXEXRPT.WriteExcelReport(); 
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {

            dwData = m_Data.INTEXDB.ICC_EVLCOST.NewRow();
            dwData["MANDANT"] = "00";
            dwData["MONTH"] = Year + Month;
            using (new LongOperation(this, "数据更新中"))
            {
                bgWoker.RunWorkerAsync();
            }
        }
        private void btnLoad_Click(object sender, EventArgs e)
        {

            DataRow dwData = SetData.ICC_EVLCOST.NewRow();
            dwData["MANDANT"] = "00";
            dwData["MONTH"] = Year + Month;
            dwData["LO"] = txtLO.Text;
            dwData["MART"] = MART;
            dwData["FART"] = FART;
            using (new LongOperation(this, "数据更新中"))
            {
                SResult = m_Data.LoadData(dwData);
                SetData.Clear();
                SetData.Merge(SResult);
            }
        }
        private void btnLoadGB14_Click(object sender, EventArgs e)
        {
            using (new LongOperation(this, "数据更新中"))
            {
                SResult = m_Data.LoadGB14(rowevl);
                SetProd.ICC_MGABEW.Clear();
                SetProd.Merge(SResult);
                GroupGABEW();
            }
        }        
        private void btnFilter_Click(object sender, RoutedEventArgs e)
        {
            string filter = "FART LIKE '%" + FART.Trim() + "%' AND MART LIKE '" + MART.Trim() + "%' AND LO LIKE '"+txtLO.Text.ToString().Trim()+"%'";
            cvEVLCOST.CustomFilter = filter;
        }
        private void btnFilterClear_Click(object sender, RoutedEventArgs e)
        {
            cvEVLCOST.CustomFilter = null;
        }
        private void UngroupButton_Click(object sender, RoutedEventArgs e)
        {
            ICollectionView cvTasks = CollectionViewSource.GetDefaultView(dlgGABEW.ItemsSource);
            if (cvTasks != null)
            {
                cvTasks.GroupDescriptions.Clear();
            }
        }

        private void GroupButton_Click(object sender, RoutedEventArgs e)
        {
            ICollectionView cvTasks = CollectionViewSource.GetDefaultView(dlgGABEW.ItemsSource);
            if (cvTasks != null && cvTasks.CanGroup == true)
            {
                cvTasks.GroupDescriptions.Clear();
                cvTasks.GroupDescriptions.Add(new PropertyGroupDescription("GABBS"));
                cvTasks.GroupDescriptions.Add(new PropertyGroupDescription("SCN"));
            }
        }
        private void GroupGABEW()
        {
            try
            {
                string result = "";
                var qGW = from GW in SetProd.Tables["ICC_MGABEW"].AsEnumerable()
                          group GW by new
                          {
                              BS = GW["GABBS"],
                              SCN = GW["SCN"],
                          }
                              into g
                              select new
                              {
                                  KEY = g.Key,
                                  KG = g.Sum(GABEW => Convert.ToDecimal(GABEW.Field<decimal>("GABKG"))),
                              };
                foreach (var GW in qGW)
                {
                    result += GW.KEY.BS + "(" + Helper.GetGB2312Value((string)GW.KEY.SCN) + "):" + GW.KG / 1000 + " kg";
                    result += " ;";
                }
                txtGroup.Text = result;
            }
            catch (Exception ex)
            { 

            }
        }
        
    }
}
